//
//  STAlert.swift
//  iPhone
//
//  Created by Toj on 9/14/22.
//

import UIKit
import SnapKit

class STAlert: UIView {
    
    private let cornerRadius: CGFloat = 8
    public var alertBackgroundColor: UIColor? { didSet {
        backgroundView.backgroundColor = alertBackgroundColor
    } }
    
    public var alertModel: STAlertModel?
    
    public var defalutAction: STActionHandle? = nil
    public var cancelAction: STActionHandle? = nil
    public var effectAction: STActionHandle? = nil
    
    public convenience init(model: STAlertModel) {
        self.init(frame: .zero)
        alertModel = model
        
        addSubview(backgroundView)
        addSubview(shadowView)
        addSubview(alertView)
        addSubview(imageView)
        // 第一次布局显示弹窗内容, 不包含图片
        setupLayoutSubviews()
        layoutIfNeeded()
        setupSubviews()
    }
    
   private override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var imageView: UIImageView = {
        let view = UIImageView()
        view.isHidden = true
        return view
    }()
    
    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapBackground(sender:)))
        view.addGestureRecognizer(tapGesture)
        return view
    }()
    
    private lazy var shadowView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        let radius: CGFloat = 3
        view.cm_shadow(color: .black, opacity: 0.5, radius: radius, offset: .zero, corner: cornerRadius)
        return view
    }()
    
    
    private lazy var alertView: STAlertView = {
        let view = STAlertView()
        view.delegate = self
        return view
    }()
    
    deinit {
        // print("-->toj: " + #function + " name: STAlert")
    }
}

extension STAlert {
    
    private func setupLayoutSubviews() {
        
        let kHeight = CGFloat.sr_height
        let sWidth = 280.ui_scale
        let alertWidth: CGFloat = sWidth > 280 ? 280 : sWidth
        let alertHeight = alertModel?.alertHeight(max: alertWidth) ?? 0
        let imageHeight = alertModel?.imageHeight ?? 0
        let top = (kHeight - alertHeight - imageHeight) * 0.5
        // print("-->toj: kHeight:\(kHeight)")
        // print("-->toj: alertHeight:\(alertHeight)")
        // print("-->toj: imageHeight:\(imageHeight)")
        backgroundView.snp.remakeConstraints { make in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(kHeight)
        }
        layoutIfNeeded()
        
        imageView.snp.remakeConstraints { make in
            make.width.equalTo(alertWidth)
            make.centerX.equalTo(self)
            make.height.equalTo(imageHeight)
            make.top.equalTo(backgroundView.snp.top).offset(top)
        }
        
        alertView.snp.remakeConstraints { make in
            make.width.equalTo(alertWidth)
            make.centerX.equalTo(self)
            make.height.equalTo(alertHeight)
            make.top.equalTo(imageView.snp.bottom)
        }
        
        shadowView.snp.remakeConstraints { make in
            make.edges.equalTo(alertView)
        }
    }

    private func setupSubviews() {
        guard let model = alertModel else { return }
        alertView.alertModel = alertModel
        let corners: CACornerMask = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        alertView.cm_corner(radius: cornerRadius, corners: corners)
        
        let urlString = model.topPicUrl
        guard urlString.count > 0 else { return }
        
        let url = URL(string: urlString)
        imageView.sd_setImage(with: url) { [weak self] image, error, type, url in
            let size = image?.size ?? .zero
            self?.imageCompletion(size: size)
        }
    }

    private func imageCompletion(size: CGSize) {
        guard let model = alertModel else { return }
        
        let iWidth = size.width
        let iHeight = size.height
        imageView.isHidden = iWidth == 0 || iHeight == 0
        if imageView.isHidden { return }
        
        let corners: CACornerMask = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
        alertView.cm_corner(radius: cornerRadius, corners: corners)
        
        let height = iHeight * model.contentWidth / iWidth
        alertModel?.imageHeight = height
        // 图片回来后2次布局, 主要布局图片大小, UI动画
        resetupLayoutSubviews()
    }
    
    private func resetupLayoutSubviews() {
        setupLayoutSubviews()
        setNeedsLayout()
        UIView.animate(withDuration: 0.15) {
            self.layoutIfNeeded()
        }
    }
    
    @objc private func didTapBackground(sender: UITapGestureRecognizer) {
        let isClose = alertModel?.isEffectClose ?? false
        guard isClose else { return }
        dismissAlert(handle: effectAction)
    }
    
    private func dismissAlert(handle: (()->Void)? = nil) {
        handle?()
        removeFromSuperview()
    }
}

extension STAlert: STAlertViewDelegate {
    
    func alertViewImageLoaded(_ view: STAlertView) {
        // 记录下图片已经load完
        alertModel?.imageLoaded = true
        
        resetupLayoutSubviews()
    }
    
    func alertView(_ view: STAlertView, didTapDefault: UIView) {
        dismissAlert(handle: defalutAction)
    }
    
    func alertView(_ view: STAlertView, didTapCancel: UIView) {
        dismissAlert(handle: cancelAction)
    }
}

